package com.agua.enturno.vista.paginas.home;

import com.agua.enturno.servicios.RubroService;
import com.agua.enturno.vista.componentes.PrestadorChoiceRenderer;
import com.agua.enturno.vista.componentes.RubroChoiceRenderer;
import com.agua.enturno.vista.dto.PrestadorDeServiciosDTO;
import com.agua.enturno.vista.dto.RubroFullDTO;
import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.ajax.form.AjaxFormComponentUpdatingBehavior;
import org.apache.wicket.markup.html.form.DropDownChoice;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.panel.Panel;
import org.apache.wicket.model.IModel;
import org.apache.wicket.model.PropertyModel;
import org.apache.wicket.spring.injection.annot.SpringBean;

import java.util.Arrays;
import java.util.List;

public class BuscadorPorRubroPanel extends Panel {

	private static final long serialVersionUID = 1L;
	
	@SpringBean
	private RubroService rubroService;
	
	@SuppressWarnings("unused")
	private RubroFullDTO rubro;
	private PrestadorDeServiciosDTO prestador;
	
	private DropDownChoice<PrestadorDeServiciosDTO> selectPrestador;

	public BuscadorPorRubroPanel(String id, final IModel<List<PrestadorDeServiciosDTO>> model) {
		super(id);
		this.setOutputMarkupId(true);
		
		List<RubroFullDTO> rubros = rubroService.findAllFull();
		rubro = rubros.get(0);
		
		@SuppressWarnings("rawtypes")
		Form form = new Form("select-rubro-form");
        add(form);
        
        DropDownChoice<RubroFullDTO> selectRubro = new DropDownChoice<RubroFullDTO>("rubros", new PropertyModel<RubroFullDTO>(this, "rubro"), rubros, new RubroChoiceRenderer());
        selectRubro.add(new AjaxFormComponentUpdatingBehavior("onchange") {
            private static final long serialVersionUID = 1L;

			protected void onUpdate(AjaxRequestTarget target) {
				
				model.setObject(null);
                target.add(BuscadorPorRubroPanel.this.getParent());
            }
        });
        form.add(selectRubro);
    	
    	selectPrestador = new DropDownChoice<PrestadorDeServiciosDTO>("prestadores", 
    			new PropertyModel<PrestadorDeServiciosDTO>(this, "prestador"), 
    			new PropertyModel<List<PrestadorDeServiciosDTO>>(this, "rubro.prestadores"), new PrestadorChoiceRenderer());
    	
    	selectPrestador.add(new AjaxFormComponentUpdatingBehavior("onchange") {
            private static final long serialVersionUID = 1L;

			protected void onUpdate(AjaxRequestTarget target) {
				
				if (prestador == null)
					model.setObject(null);
				else
					model.setObject(Arrays.asList(prestador));
				
                target.add(BuscadorPorRubroPanel.this.getParent());
            }
        });
    	    	
    	selectPrestador.setNullValid(true);
    	selectPrestador.setOutputMarkupId(true);
    	form.add(selectPrestador);
	}

}
